package cn.jekun.web.agent.action;

import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.EncryptUtil;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.bean.gen.SgSettleApply;
import cn.jekun.component.core.bean.gen.TsAccount;
import cn.jekun.component.core.service.AccountPayService;
//import cn.jekun.component.core.service.EpayLinksBankService;
import cn.jekun.web.agent.bean.BanksAccount;
import cn.jekun.web.agent.service.AccountService;
import cn.jekun.web.agent.service.BanksService;
import cn.jekun.web.agent.service.UserAgentService;

/**
 * 代理商提现
 * @author yuan
 *
 */
public class WithdrawAction extends AgentBaseAction{
//	private static final String AUTH_AGENT_MY_ACCOUNT_SETTLE="AGENT_MY_ACCOUNT_SETTLE";//提现
	
	@Resource(name=AccountService.BEAN_NAME)
	AccountService accountService;
	
	@Resource(name = BanksService.BEAN_NAME)
	BanksService banksService;
	
//	@Resource(name = EpayLinksBankService.BEAN_NAME)
//	EpayLinksBankService epayLinksBankService;
	
	@Resource(name = UserAgentService.BEAN_NAME)
    UserAgentService userAgentService;
	
	@Resource(name = AccountPayService.BEAN_NAME)
	AccountPayService accountPayService;

	/**
	 * 提现
	 * @return
	 */
	public String withdraw(){
		JSONObject jsonObject = new JSONObject();
		try
		{
			
			String tempAgentId = this.getSessionUser().getAgentId(); //获取代理商的代码
			
			JSONObject jsonAccountObject=accountPayService.querySettleAmount("", tempAgentId,Constants.TS_ACCOUNT_OWNER_TYPE.AGENT);
			String code=jsonAccountObject.getString("code");
			if(code.equals("0")){
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有找到代理商支付账户。");
				return this.writeJson(jsonObject);
			}
			
			String settleAmount=jsonAccountObject.getString("settleAmount");//可提现
			Double settleAmountDouble=new Double(settleAmount);
			
			String balance=jsonAccountObject.getString("balance");
			Double balanceDouble=new Double(balance);

			java.text.NumberFormat nf = java.text.NumberFormat.getInstance();   
			nf.setGroupingUsed(false); 
			nf.setMinimumFractionDigits(3);
			
			//最低提现金额
			double min = cn.jekun.component.core.service.AccountService.getMin();
			int days = cn.jekun.component.core.service.AccountService.getDays();
			int maxTimes = cn.jekun.component.core.service.AccountService.getMaxTimes();
			
			jsonObject.put("min",nf.format(min)) ;//最低提现金额
			
			String tips = "提现免手续费,约1-3个工作日到账";
			if(min>0){
				tips += ",最低提现"+min+"元";
			}
			if(days >0 && maxTimes >0){
				tips += ",每"+days+"天最多提现"+maxTimes+"次";
			}
			tips+="。";
			
			jsonObject.put("tips",tips) ;//
			
			jsonObject.put("isSetPay",jsonAccountObject.getString("isSetPay")) ;//是否已经设置了支付密码
			jsonObject.put("balance",balanceDouble==null?"0.00":nf.format(balanceDouble)) ;
			jsonObject.put("settleAmount",settleAmountDouble==null?"0.00":nf.format(settleAmountDouble));
			
			//获取结算银行卡号
			BanksAccount banksAccount = null;
			try{
				banksAccount = this.banksService.getBankAccount();
				
				if(banksAccount!=null){
//					banksAccount.setBankNumber(EncryptUtil.getBankNumber(banksAccount.getBankNumber()));
//     				jsonObject.put("banksAccount", banksAccount);
//					//判断最多提现次数
//					if (maxTimes >0) {
//						int times = this.accountService.getSettleTimes(banksAccount.getAccountId());
//						if (times>=maxTimes) {
//							jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//							jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，每天最多提现"+maxTimes+"次，您今天已经提现了"+times+"次");
//							return this.writeJson(jsonObject);
//						}
//					}
					banksAccount.setBankNumber(EncryptUtil.getBankNumber(banksAccount.getBankNumber()));
					jsonObject.put("bankNumber",banksAccount.getBankNumber()==null?"":banksAccount.getBankNumber());
					jsonObject.put("bankName",banksAccount.getBankName()==null?"":banksAccount.getBankName());
					jsonObject.put("accountId",banksAccount.getAccountId()==null?"":banksAccount.getAccountId());
					jsonObject.put("accountName",banksAccount.getAccountName()==null?"":banksAccount.getAccountName());
					jsonObject.put("bankNumber_sort",EncryptUtil.getBankNumber(banksAccount.getBankNumber()));//银行帐号转换*号
					
					//验证次数
					JSONObject validateResult = accountPayService.validateMaxTimes(banksAccount.getAccountId());
					if (!"1".equals(validateResult.get("code"))) {
						jsonObject.put("code", "-1");
						jsonObject.put("message", validateResult.get("message"));
						return this.writeJson(jsonObject);
					}
				}
				
			}catch(Exception e){
				
				jsonObject.put(ErrorMsg.KEY_CODE, -2);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"请先绑定提现银行卡。只能有1个默认的提现账户。");
				
				return this.writeJson(jsonObject);
				
			}
			if (banksAccount == null) {
				jsonObject.put(ErrorMsg.KEY_CODE, -2);
				
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有绑定提现银行卡号，请先绑定提现银行卡。");
				
				return this.writeJson(jsonObject);
			}
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		}catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
		
//		JSONObject jsonObject = new JSONObject();
//<<<<<<< .mine
//=======
//		//this.checkRight(AUTH_AGENT_MY_ACCOUNT_SETTLE);//检查权限
//		//获取账户余额
//		Map map = new HashMap();
//		map.put("agentId", this.getSessionUser().getAgentId());
////		map.put("agentId", "2");
//		System.out.println("agentId =" + this.getSessionUser().getAgentId());
////		TsAccount tsAccount = this.accountService.one(this.accountService.getStatementName("query"),map );
//		TsAccount tsAccount = this.userAgentService.getTsAccountByAgentId("query", this.getSessionUser().getAgentId());
//		if(tsAccount == null){
//			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//			jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有找到代理商支付账户");
//			this.saveActionError("没有找到代理商支付账户。");
//		}
//		java.text.NumberFormat nf = java.text.NumberFormat.getInstance();   
//		nf.setGroupingUsed(false); 
//		nf.setMinimumFractionDigits(3);
//
//		//最低提现金额
//		double min = this.epayLinksBankService.getMin();
//		double fee = this.epayLinksBankService.getFee();
//		int maxTimes = this.epayLinksBankService.getMaxTimes();
//		if (min > 0 && tsAccount.getBalance() < min) {
//			this.request.setAttribute("minBalance", nf.format(tsAccount.getBalance() - fee) );//可提现金额
//		    jsonObject.put("minBalance", nf.format(tsAccount.getBalance() - fee));
//		}else{
//			this.request.setAttribute("minBalance", nf.format(tsAccount.getBalance())) ;//可提现金额
//			jsonObject.put("minBalance", nf.format(tsAccount.getBalance()));
//		}
//		this.request.setAttribute("min",min);//银企互联提现最低金额(0不检查)
//		jsonObject.put("min", min);
//		this.request.setAttribute("fee",fee);//银企互联小于等于最低金额时手续费
//		jsonObject.put("fee", fee);
//		jsonObject.put("maxTimes", maxTimes);
////		request.setAttribute("balance",nf.format(tsAccount.getBalance()));
//		jsonObject.put("balance", nf.format(tsAccount.getBalance()));
//		//获取结算银行卡号
//		BanksAccount banksAccount = null;
//		try{
//			banksAccount = this.banksService.getBankAccount();
//		}catch(Exception e){
//			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//			jsonObject.put(ErrorMsg.KEY_MESSAGE,"请先绑定提现银行卡。只能有1个默认的提现账户。");
//			this.saveActionError("请先绑定提现银行卡。只能有1个默认的提现账户。");
//		}
//		if (banksAccount == null) {
//			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//			jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有绑定提现银行卡号，请先绑定提现银行卡");
//			this.saveActionError("没有绑定提现银行卡号，请先绑定提现银行卡。");
//			return this.writeJson(jsonObject);
//		}else{
//		banksAccount.setBankNumber(EncryptUtil.getBankNumber(banksAccount.getBankNumber()));//转换*号
//		//判断最多提现次数
//		if (maxTimes >0) {
//			Map countMap = new HashMap();
//			countMap.put(SgSettleApply.COL_ACCOUNT_ID, banksAccount.getAccountId());
//			SqlUtis.prepareSql(countMap, SqlUtis.getSQLRequired(countMap, SgSettleApply.COL_ACCOUNT_ID)," and to_char(a.create_time,'yyyy-mm-dd') = to_char(sysdate,'yyyy-mm-dd')");
//			int times = this.sgSettleApplyService.count(countMap);
//			if (times>=maxTimes) {
//				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//				jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，每天最多提现"+maxTimes+"次，您今天已经提现了"+times+"次");
//				return this.writeJson(jsonObject);
//			}
//		}
//		
////		this.request.setAttribute("banksAccount", banksAccount);
//		jsonObject.put("banksAccount", banksAccount);
//		}
//		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
//		System.out.println("jsonObject="+jsonObject);
//		return this.writeJson(jsonObject);
//>>>>>>> .r841
//		
//		try
//		{
//			String tempAgentId = this.getSessionUser().getAgentId(); //获取代理商的代码
//			TsAccount tsAccount = this.userAgentService.getTsAccountByAgentId("query", tempAgentId);
//		    if(tsAccount == null){
//		    	jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//		    	jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有找到代理商支付账户");
//		    	return this.writeJson(jsonObject);
//		    }
//			java.text.NumberFormat nf = java.text.NumberFormat.getInstance();   
//			nf.setGroupingUsed(false); 
//			nf.setMinimumFractionDigits(3);
//			
//			//最低提现金额
//			double min = this.epayLinksBankService.getMin();
//			double fee = this.epayLinksBankService.getFee();
//			int maxTimes = this.epayLinksBankService.getMaxTimes();
//			
//			if (min > 0 && tsAccount.getBalance() < min) {
//				jsonObject.put("minBalance",tsAccount.getBalance()==null?"":nf.format(tsAccount.getBalance() - fee));//可提现金额
//			}else{
//				jsonObject.put("minBalance",tsAccount.getBalance()==null?"":nf.format(tsAccount.getBalance())) ;//可提现金额
//			}
//			jsonObject.put("min",min) ;//银企互联提现最低金额(0不检查)
//			jsonObject.put("fee",fee) ;//银企互联低于最低金额时手续费
//			jsonObject.put("maxTimes", maxTimes);
//			jsonObject.put("balance",tsAccount.getBalance()==null?"":nf.format(tsAccount.getBalance())) ;
//			
//			//获取结算银行卡号
//			BanksAccount banksAccount = null;
//			try{
//				banksAccount = this.banksService.getBankAccount();
//				
//				if(banksAccount!=null){
//					banksAccount.setBankNumber(EncryptUtil.getBankNumber(banksAccount.getBankNumber()));
//     				jsonObject.put("banksAccount", banksAccount);
//					//判断最多提现次数
//					if (maxTimes >0) {
//						Map countMap = new HashMap();
//						countMap.put(SgSettleApply.COL_ACCOUNT_ID, banksAccount.getAccountId());
//						SqlUtis.prepareSql(countMap, SqlUtis.getSQLRequired(countMap, SgSettleApply.COL_ACCOUNT_ID)," and to_char(a.create_time,'yyyy-mm-dd') = to_char(sysdate,'yyyy-mm-dd')");
//						int times = this.sgSettleApplyService.count(countMap);
//						if (times>=maxTimes) {
//							jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//							jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，每天最多提现"+maxTimes+"次，您今天已经提现了"+times+"次");
//							return this.writeJson(jsonObject);
//						}
//					}
//				}
//				
//			}catch(Exception e){
//				
//				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//				
//				jsonObject.put(ErrorMsg.KEY_MESSAGE,"请先绑定提现银行卡。只能有1个默认的提现账户。");
//				
//				return this.writeJson(jsonObject);
//				
//			}
//			if (banksAccount == null) {
//				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//				
//				jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有绑定提现银行卡号，请先绑定提现银行卡。");
//				
//				return this.writeJson(jsonObject);
//			}
//			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
//			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
//		}catch (BusinessException e) {
//			jsonObject = JSONObject.fromObject(e.getErrorMsg());
//		} catch (Exception e) {
//			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
//			e.printStackTrace();
//		}
//		
//		
//		
////		JSONObject jsonObject = new JSONObject();
////		//this.checkRight(AUTH_AGENT_MY_ACCOUNT_SETTLE);//检查权限
////		//获取账户余额
//////		map.put("agentId", this.getSessionUser().getAgentId());
//////		map.put("agentId", "2");
//////		System.out.println("agentId =" + this.getSessionUser().getAgentId());
//////		TsAccount tsAccount = this.accountService.one(this.accountService.getStatementName("query"),map );
////		TsAccount tsAccount = this.userAgentService.getTsAccountByAgentId("query", this.getSessionUser().getAgentId());
////		if(tsAccount == null){
////			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
////			jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有找到代理商支付账户");
////			this.saveActionError("没有找到代理商支付账户。");
////			return this.writeJson(jsonObject);
////		}
////		java.text.NumberFormat nf = java.text.NumberFormat.getInstance();   
////		nf.setGroupingUsed(false); 
////		nf.setMinimumFractionDigits(3);
////
////		//最低提现金额
////		double min = this.epayLinksBankService.getMin();
////		double fee = this.epayLinksBankService.getFee();
////		if (min > 0 && tsAccount.getBalance() < min) {
////			this.request.setAttribute("minBalance", nf.format(tsAccount.getBalance() - fee) );//可提现金额
////		    jsonObject.put("minBalance", nf.format(tsAccount.getBalance() - fee));
////		}else{
////			this.request.setAttribute("minBalance", nf.format(tsAccount.getBalance())) ;//可提现金额
////			jsonObject.put("minBalance", nf.format(tsAccount.getBalance()));
////		}
////		this.request.setAttribute("min",min);//银企互联提现最低金额(0不检查)
//////		jsonObject.put("min", min);
////		jsonObject.put("min","100");
//////		this.request.setAttribute("fee",fee);//银企互联低于最低金额时手续费
////		
//////		jsonObject.put("fee", fee);
////		jsonObject.put("fee", "10");
////		
//////		request.setAttribute("balance",nf.format(tsAccount.getBalance()));
////		jsonObject.put("balance", nf.format(tsAccount.getBalance()));
////		//获取结算银行卡号
////		BanksAccount banksAccount = null;
////		try{
////			banksAccount = this.banksService.getBankAccount();
////		
////		if (banksAccount == null) {
////			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
////			jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有绑定提现银行卡号，请先绑定提现银行卡");
////			this.saveActionError("没有绑定提现银行卡号，请先绑定提现银行卡。");
////			return this.writeJson(jsonObject);
////		}else{
////		banksAccount.setBankNumber(EncryptUtil.getBankNumber(banksAccount.getBankNumber()));//转换*号
//////		this.request.setAttribute("banksAccount", banksAccount);
////		jsonObject.put("banksAccount", banksAccount);
////		}
////		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
////		}catch (BusinessException e) {
////			jsonObject = JSONObject.fromObject(e.getErrorMsg());
////		} catch (Exception e) {
////		    jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
////		   
////		}
////		return this.writeJson(jsonObject);
////	
//		return this.writeJson(jsonObject);
		
	}
	/**
	 * 提现确认
	 */
	public String confirm(){
//		this.checkRight(AUTH_AGENT_MY_ACCOUNT_SETTLE);//检查权限
		
		String accountId = request.getParameter("accountId");//提现账户代码
		String amountStr = request.getParameter("amount");//提现金额
		if (StringUtils.isBlank(accountId)) {
			this.saveActionError("请选择提现的银行账户");
		    return "/agent/Withdraw/withdraw.do";
		}
//		//判断最多提现次数
//		int maxTimes = this.epayLinksBankService.getMaxTimes();
//		if (maxTimes >0) {
//			int times = this.accountService.getSettleTimes(accountId);
//			if (times>=maxTimes) {
//				this.saveActionError("对不起，每天最多提现"+maxTimes+"次，您今天已经提现了"+times+"次");
//				return "/agent/Withdraw/withdraw.do";
//			}
//		}
		//检查提现金额
		if (StringUtils.isBlank(amountStr)) {
			this.saveActionError("请输入提现的金额");
			return "/agent/Withdraw/withdraw.do";
		}
		double amount = 0;
		try {
			amount = Double.parseDouble(amountStr);
		} catch (Exception e) {
			this.saveActionError("提现金额必须是有效的数字");
			return "/agent/Withdraw/withdraw.do";
		}
		if(amount <=0){
			this.saveActionError("提现金额必须大于0");
			return "/agent/Withdraw/withdraw.do";
		}
		return "/agent/withdraw_confirm.jsp";
		
	}
	/**
	 * 提现申请
	 * @return
	 */
	public String settleApply(){
		JSONObject jsonObject =  new JSONObject();
//		this.checkRight(AUTH_AGENT_MY_ACCOUNT_SETTLE);//检查权限
		String accountId = request.getParameter("accountId");//提现账户代码
		String bankNumber = request.getParameter("bankNumber");//银行账户
		String bankName = request.getParameter("bankName");//银行名称
		String accountName = request.getParameter("accountName");//账户姓名
		String amountStr = request.getParameter("amount");//提现金额
		String paypwd = request.getParameter("paypwd");//支付密码
		String _sign_key = request.getParameter("_sign_key");//加密
		
		if (StringUtils.isBlank(accountId)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请选择提现的银行账户");
			this.saveActionError("对不起，请选择提现的银行账户");
			return this.writeJson(jsonObject);
//			return "/agent/Withdraw/confirm.do";
		}
		//判断最多提现次数
//		int maxTimes = this.epayLinksBankService.getMaxTimes();
//		if (maxTimes >0) {
//			int times = this.accountService.getSettleTimes(accountId);
//			if (times>=maxTimes) {
//				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//				jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，每天最多提现"+maxTimes+"次，您今天已经提现了"+times+"次");
//				return this.writeJson(jsonObject);
//			}
//		}
		if (StringUtils.isBlank(paypwd)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请输入支付密码");
			this.saveActionError("对不起，请输入支付密码");
			return this.writeJson(jsonObject);
//			return "/agent/Withdraw/confirm.do";
		}
		//检查提现金额
		if (StringUtils.isBlank(amountStr)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，请输入提现的金额");
			return this.writeJson(jsonObject);
//			this.saveActionError("对不起，请输入提现的金额");
//			return "/agent/Withdraw/confirm.do";
		}
		double amount = 0;
		try {
			amount = Double.parseDouble(amountStr);
		} catch (Exception e) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，提现金额必须是有效的数字");
			return this.writeJson(jsonObject);
			//this.saveActionError("对不起，提现金额必须是有效的数字");
            //return "/agent/Withdraw/confirm.do";
		}
		if(amount <=0){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，提现金额必须大于0");
			return this.writeJson(jsonObject);
//			this.saveActionError("对不起，提现金额必须大于0");
//			return "/agent/Withdraw/confirm.do";
		}
		if (StringUtils.isBlank(bankNumber)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法银行账户");
			return this.writeJson(jsonObject);
//			this.saveActionError("对不起，非法银行账户");
//			return "/shop/Withdraw/confirm.do";
		}
		if (StringUtils.isBlank(bankName)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法银行名称");
			return this.writeJson(jsonObject);
//			this.saveActionError("对不起，非法银行名称");
//			return "/shop/Withdraw/confirm.do";
		}
		if (StringUtils.isBlank(accountName)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，非法账户姓名");
			return this.writeJson(jsonObject);
//			this.saveActionError("对不起，非法账户姓名");
//			return "/shop/Withdraw/confirm.do";
		}
		String md5 = EncryptUtil.md5(accountId+amountStr+bankNumber+bankName+accountName+paypwd);
		if (!md5.equals(_sign_key)) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"非法提交");
			return this.writeJson(jsonObject);
//			this.saveActionError("非法提交");
//			return "/shop/Withdraw/confirm.do";
		}
		//获取账户信息
//		Map map = new HashMap();
//		map.put("agentId", this.getSessionUser().getAgentId());
//		TsAccount tsAccount = this.accountService.one(this.accountService.getStatementName("query"),map );
		
		String agentId=this.getSessionUser().getAgentId();
		//获取可提现金额 
		JSONObject jsonAccountObject=accountPayService.querySettleAmount("", agentId,Constants.TS_ACCOUNT_OWNER_TYPE.AGENT);
		String settleCode=jsonAccountObject.getString("code");
		if(settleCode.equals("0")){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有找到商家支付账户。");
			return this.writeJson(jsonObject);
		}
//		String amountCount=jsonAccountObject.getString("amount");
//		Double settleAmount=new Double(amountCount);
				
		TsAccount tsAccount = this.accountService.getAccountByOne("query",agentId);
		if(tsAccount == null){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，没有找到代理商支付账户。");
			return this.writeJson(jsonObject);
//			this.saveActionError("对不起，没有找到代理商支付账户。");
//			return "/agent/Withdraw/confirm.do";
		}
		//验证支付密码
		System.out.println(paypwd+"::"+tsAccount.getPassword());
		if(StringUtils.isBlank(paypwd) || !tsAccount.getPassword().equals(paypwd)){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，支付密码不正确");
			return this.writeJson(jsonObject);
			//this.saveActionError("对不起，支付密码不正确");
            //return "/agent/Withdraw/confirm.do";
		}
//		//验证可提现余额
//		if(settleAmount < amount){
//			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，可提现余额不足。");
//			return this.writeJson(jsonObject);
////			this.saveActionError("对不起，余额不足");
////			return "/agent/Withdraw/confirm.do";
//		}
//		//最低提现金额
//		double min = this.epayLinksBankService.getMin();
//		double fee = 0;
//		if (min > 0 && amount <= min) {//提现金额小于等于最小金额
//			fee = this.epayLinksBankService.getFee();//手续费
//		}
//		if (min > 0 && amount < min && ( amount + fee ) > settleAmount ) {//提现金额小于最低提现金额,并且余额小于最低提现金额(min-fee)
//			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
//			jsonObject.put(ErrorMsg.KEY_MESSAGE,"对不起，提现金额小于等于"+min+"元收取"+fee+"元手续费,目前您可提现金额是"+(settleAmount - fee )+"元");
//			return this.writeJson(jsonObject);
////			this.saveActionError("对不起，提现金额小于"+min+"元收取"+fee+"元手续费,目前您可提现金额是"+(tsAccount.getBalance() - fee )+"元");
////			return "/shop/Withdraw/confirm.do";
//		}
		//提现申请
		String settleApplyId = null;//提现申请代码
		try{
			
			JSONObject jsonSettleApply=this.accountPayService.settleApply("", tsAccount.getAccountId(), amount+"", "", accountId,paypwd,Constants.SG_APPLY_TYPE.AGENT_WEB,this.getUserId());
			String code=jsonSettleApply.getString("code");
			String message=jsonSettleApply.getString("message");
			
			if(code.equals("0")){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,message);
			}
			settleApplyId=jsonSettleApply.getString("applyId");
			
			//settleApplyId = this.banksService.settleApply(this.getSessionUser().getUserId(),accountId, amount,fee,paypwd);
			this.logService.addAgentAuditLog("", "申请提现成功，提现申请代码:"+settleApplyId);//记录操作日志
		}catch(Exception e){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"增加提现申请发生错误:"+e.getMessage());
			return this.writeJson(jsonObject);
//			this.saveActionError("增加提现申请发生错误:"+e.getMessage());
//			return "/agent/withdraw_result.jsp";
		}
		if(settleApplyId == null){
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"增加提现申请失败");
			return this.writeJson(jsonObject);
//			this.saveActionError("增加提现申请失败");
//			return "/agent/withdraw_result.jsp";
		}
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"申请成功,请等待银行处理");
		return this.writeJson(jsonObject);
//		this.saveActionMessage("申请成功,请等待银行处理");
//		return "/agent/withdraw_result.jsp";
	}
	
	/**
	 * 提现记录
	 * @return
	 */
	public String querySettle(){
		String agentId = this.getSessionUser().getAgentId();
	    JSONObject jsonObject = new JSONObject();
	    JSONArray jsonoArray = new JSONArray();
	    String beginMoney=request.getParameter("beginMoney");
		String endMoney=request.getParameter("endMoney");
		String bankName=request.getParameter("bankName");
		String beginDate=request.getParameter("commitTime_BEGIN");
		String endDate=request.getParameter("commitTime_END");
//		Map hashMap = null;
//	    formMap.put("agentId", agentId);
//		SqlUtis.convertBetweenValue(formMap, "commitTime");
//		SqlUtis.prepareSql(formMap
//				,SqlUtis.getSQL(formMap, "a."+SgSettleApply.COL_COMMIT_TIME,"commitTime", Types.DATE)
//				,SqlUtis.getSQL(formMap, "u."+RsUser.COL_REAL_NAME, "realName", Types.VARCHAR,SqlUtis.LIKE)
//				,SqlUtis.getSQL(formMap, "u."+RsUser.COL_USER_NAME, "userName", Types.VARCHAR,SqlUtis.LIKE)
//				);
		try{
//		this.resultList= this.banksService.list(this.banksService.getStatementName("listSettleApply"), formMap,page);
//		this.resultList = this.banksService.getBankList("listSettleApply",agentId,page);
		this.resultList = this.banksService.listSettleApply(agentId, beginDate, endDate, beginMoney, endMoney,bankName, page);
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
		jsonObject.put("resultList", resultList);
		jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());	
	    jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());	
		jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
		jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
		}catch(Exception e){
			e.printStackTrace();
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失敗");
		}
		return writeJson(jsonObject);
		
	/*	String agentId = this.getSessionUser().getAgentId();
		formMap.put("agentId", agentId);
		SqlUtis.convertBetweenValue(formMap, "commitTime");
		SqlUtis.prepareSql(formMap
				,SqlUtis.getSQL(formMap, "a."+SgSettleApply.COL_COMMIT_TIME,"commitTime", Types.DATE)
				,SqlUtis.getSQL(formMap, "u."+RsUser.COL_REAL_NAME, "realName", Types.VARCHAR,SqlUtis.LIKE)
				,SqlUtis.getSQL(formMap, "u."+RsUser.COL_USER_NAME, "userName", Types.VARCHAR,SqlUtis.LIKE)
				);
		this.resultList = this.banksService.list(this.banksService.getStatementName("listSettleApply"), formMap,page);
		return "/agent/withdraw_settle.jsp";*/
	}
	
	public String getBindBankCard(){
		return "/agentadmin/Banks/getBindBankCard.do";
	}

}
